<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.stationId ? $t('crud.addTitle') : $t('temp.modify')"
    :close-on-click-modal="false"
    width="760px"
  >
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="100px"
      style="min-width:630px;"
      class="form-box"
      @submit.prevent
    >
      <el-form-item
        class="stationName"
        :label="$t('station.stationNames')"
        prop="stationName"
        style="width:624px;"
      >
        <el-input
          v-model="dataForm.stationName"
          maxlength="50"
          show-word-limit
          @change="checkStationNames"
        />
      </el-form-item>
      <el-form-item
        :label="$t('admin.stationImg')"
        prop="pic"
      >
        <img-upload v-model="dataForm.pic" />
        <div
          v-if="dataForm.pic"
          class="default-btn"
          @click="dataForm.pic = ''"
        >
          删除
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('admin.phoNumber')"
        prop="phone"
      >
        <el-col :span="16">
          <el-col :span="6">
            <el-input
              v-model="dataForm.phonePrefix"
              :placeholder="$t('admin.areaCode')"
              maxlength="10"
              @change="checkPhonePrefix"
            />
          </el-col>
          <el-col :span="1">
            <span>——</span>
          </el-col>
          <el-col :span="14">
            <el-input
              v-model="dataForm.phone"
              :placeholder="$t('admin.number')"
              maxlength="11"
              @change="checkPhone"
            />
          </el-col>
        </el-col>
        <el-col :span="8" />
      </el-form-item>
      <el-form-item
        :label="$t('admin.businTime')"
        prop="shopTime"
      >
        <el-time-picker
          v-model="timeDateModeVO.shopTime[0]"
          :clearable="false"
          format="HH:mm"
          :placeholder="$t('admin.businStartTime')"
          @change="startChange"
        />
        <span style="margin: 0 10px;">{{ $t('time.tip') }}</span>
        <el-time-picker
          v-model="timeDateModeVO.shopTime[1]"
          :clearable="false"
          format="HH:mm"
          :placeholder="$t('admin.businEndTime')"
          @change="endChange"
        />
      </el-form-item>
      <el-form-item :label="$t('station.businessStatus')">
        <el-radio-group
          v-model="status"
          :disabled="dataForm.status > 1"
        >
          <el-radio :label="1">
            {{ $t('station.business') }}
          </el-radio>
          <el-radio :label="0">
            {{ $t('station.close') }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item
        style="margin-bottom:0"
        :label="$t('shopProcess.addr')"
        prop="areaInfo"
      >
        <div class="area-select">
          <el-form-item prop="province">
            <el-select
              v-model="dataForm.provinceId"
              :placeholder="$t('tip.select')"
              @change="onSelectProvince"
            >
              <el-option
                v-for="province in provinceList"
                :key="province.areaId"
                :label="province.areaName"
                :value="province.areaId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('address.city')"
            label-width="50px"
            prop="city"
          >
            <el-select
              v-model="dataForm.cityId"
              :placeholder="$t('address.city')"
              @change="onSelectCity"
            >
              <el-option
                v-for="city in cityList"
                :key="city.areaId"
                :label="city.areaName"
                :value="city.areaId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('address.area')"
            label-width="50px"
            prop="area"
          >
            <el-select
              v-model="dataForm.areaId"
              :placeholder="$t('address.area')"
              @change="onSelectArea"
            >
              <el-option
                v-for="area in areaList"
                :key="area.areaId"
                :label="area.areaName"
                :value="area.areaId"
              />
            </el-select>
          </el-form-item>
        </div>
      </el-form-item>
      <el-form-item
        class="addr"
        :label="$t('shopProcess.detailAddr')"
        prop="addr"
      >
        <el-input
          v-model="dataForm.addr"
          maxlength="100"
          show-word-limit
          @change="onMapLocation"
        />
      </el-form-item>
      <el-form-item>
        <div class="map">
          <tmap
            ref="tmapRef"
            :lat-lng="latLng"
            @change-lat-lng="onChangeLatLng"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
import ImgUpload from '@/components/img-upload/index.vue'

const emit = defineEmits(['refreshDataList'])
const dataForm = ref({
  stationId: null,
  stationName: null,
  pic: null,
  phonePrefix: null,
  phone: null,
  startTime: '',
  endTime: '',
  status: 1,
  provinceId: null,
  province: null,
  cityId: null,
  city: null,
  areaId: null,
  area: null,
  addr: null,
  lng: null,
  lat: null,
  timeDateModeVO: {}
})
const timeDateModeVO = ref({
  shopTime: [new Date(2020, 1, 1, 8, 0, 0), new Date(2020, 1, 1, 20, 0, 0)]
})

// eslint-disable-next-line no-unused-vars
const validateProvince = (rule, value, callback) => {
  if (!dataForm.value.province) {
    callback(new Error($t('admin.seleProv')))
  } else if (!dataForm.value.city) {
    callback(new Error($t('admin.seleCity')))
  } else if (!dataForm.value.area) {
    callback(new Error($t('admin.seleDC')))
  } else {
    callback()
  }
}
// eslint-disable-next-line no-unused-vars
const validateShopTime = (rule, value, callback) => {
  if (!timeDateModeVO.value.shopTime) {
    callback(new Error($t('admin.seleBusTime')))
  } else {
    callback()
  }
}
const validateStationName = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('admin.stationNameNoNull')))
  } else {
    callback()
  }
}
const validateAddr = (rule, value, callback) => {
  if (!value.trim()) {
    callback(new Error($t('admin.addrNoNull')))
  } else {
    callback()
  }
}
const dataRule = {
  stationName: [
    { required: true, message: $t('admin.stationNameNoNull'), trigger: 'blur' },
    { validator: validateStationName, trigger: 'blur' }
  ],
  areaInfo: [
    { required: true, validator: validateProvince, trigger: 'blur' }
  ],
  shopTime: [
    { validator: validateShopTime, trigger: 'blur' }
  ],
  addr: [
    { required: true, message: $t('admin.addrNoNull'), trigger: 'blur' },
    { validator: validateAddr, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: $t('admin.numberNoNull'), trigger: 'blur' }
  ]
}

const startChange = (val) => {
  if (!val) {
    timeDateModeVO.value.shopTime[0] = new Date(2020, 1, 1, 8, 0, 0)
  }
}

const endChange = (val) => {
  if (!val) {
    timeDateModeVO.value.shopTime[1] = new Date(2020, 1, 1, 20, 0, 0)
  }
}

const cityList = ref([])
const areaList = ref([])
const provinceList = ref([])
const visible = ref(false)
const show = ref(false)
const isSubmit = ref(false)
const status = ref(1)
const dataFormRef = ref(null)
const init = (stationId) => {
  dataForm.value.stationId = stationId || 0
  visible.value = true
  show.value = false
  isSubmit.value = false
  nextTick(() => {
    status.value = 1
    dataFormRef.value?.resetFields()
    cityList.value = []
    areaList.value = []
    dataForm.value.provinceId = null
    dataForm.value.cityId = null
    dataForm.value.areaId = null
    dataForm.value.phonePrefix = null
    timeDateModeVO.value = {
      shopTime: [new Date(2020, 1, 1, 8, 0, 0), new Date(2020, 1, 1, 20, 0, 0)]
    }
    listAreaByParentId().then(({ data }) => {
      provinceList.value = data
      if (dataForm.value.stationId) {
        getDataInfo()
      }
    })
  })
}
defineExpose({ init })

/**
 * 获取店铺详情数据
 */
const getDataInfo = () => {
  http({
    url: http.adornUrl('/admin/station/info/' + dataForm.value.stationId),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    dataForm.value = data
    status.value = dataForm.value.status === 1 ? 1 : 0
    timeDateModeVO.value = JSON.parse(data.timeDate)
    listAreaByParentId(data.provinceId).then(({ data }) => {
      cityList.value = data
    })
    listAreaByParentId(data.cityId).then(({ data }) => {
      areaList.value = data
      if (dataForm.value.lng && dataForm.value.lat) {
        latLng.value = {
          lng: dataForm.value.lng,
          lat: dataForm.value.lat
        }
      }
    })
  })
}

const listAreaByParentId = (pid) => {
  let paramData
  if (!pid) {
    paramData = { level: 1 }
  } else {
    paramData = { pid }
  }
  return http({
    url: http.adornUrl('/admin/area/listByPid'),
    method: 'get',
    params: http.adornParams(paramData)
  })
}

const getCurrentChild = (curList, curId) => {
  for (const item of curList) {
    if (item.areaId === curId) {
      return {
        curNode: item,
        areas: item.areas
      }
    }
  }
}

// 修改经纬度
const onChangeLatLng = (latLngInfo) => {
  const { lng, lat } = latLngInfo
  latLng.value = latLngInfo
  dataForm.value.lng = lng
  dataForm.value.lat = lat
}

/**
 * 选择省
 * @param val
 */
const onSelectProvince = (val) => {
  dataForm.value.cityId = null
  dataForm.value.city = ''
  areaList.value = []
  dataForm.value.areaId = null
  dataForm.value.area = ''
  const { curNode, areas } = getCurrentChild(provinceList.value, val)
  if (areas) {
    cityList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      cityList.value = data
    })
  }
  onGetProvinceName() // 获取省名称
  onMapLocation(true)
}

/**
 * 选择市
 * @param val
 */
const onSelectCity = (val) => {
  dataForm.value.areaId = null
  dataForm.value.area = ''
  const { curNode, areas } = getCurrentChild(cityList.value, val)
  if (areas) {
    areaList.value = areas
  } else {
    listAreaByParentId(val).then(({ data }) => {
      curNode.areas = data
      areaList.value = data
    })
  }
  onGetCityName() // 获取市名称
  onMapLocation(true)
}

const onSelectArea = () => {
  onGetDistrictName() // 获取区名称
  onMapLocation(true)
}

const checkStationNames = () => {
  dataForm.value.stationName = dataForm.value.stationName.trim()
}

const checkPhonePrefix = () => {
  if (dataForm.value.phonePrefix) {
    const reg = /^[0-9]*$/
    if (!reg.test(dataForm.value.phonePrefix)) {
      message($t('admin.onlyInNum'))
      dataForm.value.phonePrefix = null
      return false
    }
  }
}

const checkPhone = () => {
  if (dataForm.value.phone) {
    const reg = /^[0-9]*$/
    if (!reg.test(dataForm.value.phone)) {
      message($t('admin.onlyInNum'))
      dataForm.value.phone = null
      return false
    }
  }
}

const isEditAddr = ref(false)
/**
 * 表单提交
 */
const onSubmit = () => {
  if (isEditAddr.value) {
    ElMessage.info($t('admin.mapPosi'))
    return
  }
  onGetAreaName()
  dataForm.value.lng = latLng.value.lng
  dataForm.value.lat = latLng.value.lat
  const timeDateMode = timeDateModeVO.value
  if (timeDateMode.shopTime) {
    if (timeDateMode.shopTime[0] instanceof Date) {
      timeDateMode.shopTime[0] = timeDateMode.shopTime[0].getTime()
    }
    if (timeDateMode.shopTime[1] instanceof Date) {
      timeDateMode.shopTime[1] = timeDateMode.shopTime[1].getTime()
    }
    const oneDay = 24 * 60 * 60 * 1000 // 一天对应的毫秒数
    // 如果结束时间小于开始时间，则给结束时间加一天，表示第二天的时间
    if (timeDateMode.shopTime[1] < timeDateMode.shopTime[0]) {
      timeDateMode.shopTime[1] = new Date(timeDateMode.shopTime[1] + oneDay)
    }
    dataForm.value.timeDate = JSON.stringify(timeDateMode)
  }
  if (!dataForm.value.areaId) {
    ElMessage.error($t('shopProcess.addrInputTips'))
    return
  }
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit.value) {
        return false
      }
      isSubmit.value = true
      dataForm.value.status = dataForm.value.status > 1 ? dataForm.value.status : status.value
      http({
        url: http.adornUrl('/admin/station'),
        method: dataForm.value.stationId ? 'put' : 'post',
        data: http.adornData(dataForm.value)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit.value = false
      })
    }
  })
}

const message = (msg) => {
  ElMessage({
    message: msg,
    type: 'error',
    duration: 1500
  })
}

const tmapRef = ref(null)
const latLng = ref(null)
/**
 * 定位地图
 * @param isTrue
 */
const onMapLocation = (isTrue) => {
  let address = ''
  const { provinceId, province, cityId, city, areaId, area, addr } = dataForm.value
  if (isTrue) {
    // 选择省市区时，定位地图
    if (provinceId) {
      address = province
      tmapRef.value.onSetZoom(6)
      if (cityId) {
        address = address + city
        tmapRef.value.onSetZoom(10)
        if (areaId) {
          address = address + area
          tmapRef.value.onSetZoom(18)
          if (addr) {
            // 详细地址
            address = address + addr
            tmapRef.value.onSetZoom(18)
          }
        }
      }
    }
    if (address) {
      tmapRef.value?.onGetLocation(address).then(res => {
        onChangeLatLng(res)
      })
    }
  } else {
    if (!provinceId || !cityId || !areaId) {
      dataForm.value.detailAddress = null
      ElMessage({
        message: $t('admin.selePCD'),
        type: 'error',
        duration: 1000
      })
      return
    }
    tmapRef.value.onGetAddress(latLng.value).then(res => {
      if (res && res.pois && res.pois.length) {
        // 优先使用短地址，如果未返回短地址，则使用描述精确性较高带省市区的地址，最后使用以行政区划+道路+门牌号等信息组成的标准格式化地址
        dataForm.value.detailAddress = res.pois[0].address || res.formatted_addresses?.recommend || res.address
      }
    })
    tmapRef.value.onSetZoom(18)
  }
}

// 通过省市区id,得到省市区名称
const onGetAreaName = () => {
  onGetProvinceName() // 保存省名字
  onGetCityName() // 保存市名字
  onGetDistrictName() // 保存区名字
}
const onGetProvinceName = () => {
  for (let i = 0; i < provinceList.value.length; i++) {
    if (provinceList.value[i].areaId === dataForm.value.provinceId) {
      // 将省名字保存起来
      dataForm.value.province = provinceList.value[i].areaName
    }
  }
}

const onGetCityName = () => {
  for (let i = 0; i < cityList.value.length; i++) {
    if (cityList.value[i].areaId === dataForm.value.cityId) {
      // 将市名字保存起来
      dataForm.value.city = cityList.value[i].areaName
    }
  }
}

const onGetDistrictName = () => {
  for (let i = 0; i < areaList.value.length; i++) {
    if (areaList.value[i].areaId === dataForm.value.areaId) {
      // 将市名字保存起来
      dataForm.value.area = areaList.value[i].areaName
    }
  }
}
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 500px;
}
.area-select {
  display: flex;
  margin-bottom: 18px;
}
:deep(.el-form-item__content .el-col) {
  display: flex;
}
:deep(.el-form-item__content .up-img-box) {
  margin-right: 100%;
}
:deep(.up-img-box .plugin-images .el-upload--picture-card),
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 100px;
  height: 100px;
}
</style>
